package com.ysh.servlet;

import com.ysh.domain.Student;
import com.ysh.domain.User;
import com.ysh.service.UserService;
import com.ysh.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    // 创建service层对象
    private UserService service = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 统一编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 通过method来获取要执行的功能：login
        String method = req.getParameter("method");
        // 判断跳转不同方法完成不同功能
        if ("login".equals(method)){
            login(req,resp);
        }
        if ("findAll".equals(method)){
            findAll(req,resp);
        }
    }

    // 登录功能
    public void login(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        // 获取页面传入数据
        String username = request.getParameter("username");// 传入用户名
        String pwd = request.getParameter("password"); // 页面传入密码
        // 验证
        User u = service.login(username,pwd);
        // 对结果进行处理
        if (u != null){
            // 跳转到主页
            request.getRequestDispatcher("/user?method=findAll").forward(request,response);
        }else{
            response.getWriter().write("登录失败！，即将返回登录页面...");
        }
    }

    // 遍历
    private void findAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Student> list = service.findAll();
        // 将list结果集带回jsp作用域展示
        req.setAttribute("listStudent",list);
        // 请求转发
        req.getRequestDispatcher("/main.jsp").forward(req,resp);

    }
}
